package com.xyxy.web;

import com.xyxy.pojo.User;
import com.xyxy.service.UserService;
import com.xyxy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @Desc: 已被userservlet替代
* @param:
* @return:
*/
public class RegistServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//      1、获取请求的参数,表单的name属性值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");//验证码

//      2、检查验证码是否正确  写死，要求验证码为abcde
        if ("abcde".equalsIgnoreCase(code)) {

//          3、如果验证码正确，检查用户名是否可用
            if (userService.isExistsUsername(username)) {
                //如果不可用
                System.out.println("用户名" + username + "已存在！");

                //把信息回显，保存到request域中
                request.setAttribute("msg","用户名已存在！");
                request.setAttribute("username",username);
                request.setAttribute("email",email);

                //跳回注册页面
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
            } else {
                //如果可用,调用Service保存到数据库,跳到注册成功束面regist_success.html
                userService.registUser(new User(null, username, password, email));
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response);
            }
        } else {
            //把信息回显，保存到request域中
            request.setAttribute("msg","验证码错误！");
            request.setAttribute("username",username);
            request.setAttribute("email",email);

            //不正确,跳回注册页面
            System.out.println("验证码" + code + "错误!");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
        }
    }

}
